package com.shenzhen.horselive;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatDelegate;

import com.bytedance.sdk.openadsdk.TTAdConfig;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.flqy.baselibrary.BaseApp;
import com.meiqia.core.callback.OnInitCallback;
import com.meiqia.meiqiasdk.util.MQConfig;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshFooterCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.shenzhen.horselive.common.manager.PlaceManager;
import com.shenzhen.horselive.network.RetrofitClient;
import com.shenzhen.horselive.utils.GetJsonDataUtil;
import com.shenzhen.horselive.widget.MyLoadViewFactory;
import com.shenzhen.horselive.wx.WXManager;
import com.shizhefei.mvc.MVCHelper;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Locale;

import cn.jpush.android.api.JPushInterface;
import me.jessyan.autosize.AutoSizeConfig;
import me.jessyan.autosize.onAdaptListener;
import me.jessyan.autosize.utils.AutoSizeLog;


public class App extends BaseApp {
    private static final String TAG = "MillionContacts";//更新签名   应用名字。
    private static App instance;
    private Handler mainThreadHandler;
    private User user;
    private Cache cache;
    private PlaceManager placeManager;
    private boolean umConfigureInited = false;
    //private PushManager mPushManager;

    public static String mHuanxinUserName;
    public static String mHuanxinPassword;

    //腾讯地图的keyTXHBZ-XM7WQ-7JK5O-GOBYX-I6RWK-YSBVX正式
    //测试322BZ-NTN3D-NPU4P-HPJDC-TNGQH-B4F5G
    public static  String mapkey = "TXHBZ-XM7WQ-7JK5O-GOBYX-I6RWK-YSBVX";


    //美洽对话的key
    public  static   String  meiqikey="cef72cef77c2bebdf87fc6fb93b65c9d";


    public static App getInstance() {
        return instance;
    }

    private String ran;

    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.red_common, android.R.color.white);//全局设置主题颜色
                return new MaterialHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }


    //获取城市和地区的code
    public   static String  codeString  =null;



    @Override
    public void onCreate() {
        super.onCreate();
//        if (BuildConfig.DEBUG) {
//            if (LeakCanary.isInAnalyzerProcess(this)) {
//                // This process is dedicated to LeakCanary for heap analysis.
//                // You should not init your app in this process.
//                return;
//            }
//            LeakCanary.install(this);
//        }
        instance = this;
        cache = new Cache();
        user = new User();
        mainThreadHandler = new Handler(Looper.getMainLooper());
        MVCHelper.setLoadViewFactory(new MyLoadViewFactory());
        RetrofitClient.setDebug(isDebug());
        placeManager = new PlaceManager();
        placeManager.asynInitRegion();
        //强烈建议在应用对应的Application#onCreate()方法中调用，避免出现content为null的异常

        ran = String.valueOf(100000);
        //初始化客服第三方
        initMeiqia();
        //初始化微信
        WXManager.getInstance().init(this);

        //初始化citycode
        GetJsonDataUtil.getInstance().initCityCode();
        //初始化极光
        JPushInterface.setDebugMode(BuildConfig.DEBUG);
        JPushInterface.init(this);
        //广告的sdk
        initChuanShanjia();
    }

    private void initChuanShanjia() {
        //强烈建议在应用对应的Application#onCreate()方法中调用，避免出现content为null的异常
        TTAdSdk.init(this,
                new TTAdConfig.Builder()
                        .appId("5111459")
                        .useTextureView(true) //使用TextureView控件播放视频,默认为SurfaceView,当有SurfaceView冲突的场景，可以使用TextureView
                        .appName(getResources().getString(R.string.app_name))
                        .titleBarTheme(TTAdConstant.TITLE_BAR_THEME_DARK)
                        .allowShowNotify(true) //是否允许sdk展示通知栏提示
                        .allowShowPageWhenScreenLock(true) //是否在锁屏场景支持展示广告落地页
                        .debug(BuildConfig.DEBUG) //测试阶段打开，可以通过日志排查问题，上线时去除该调用
                        .directDownloadNetworkType(TTAdConstant.NETWORK_STATE_WIFI) //允许直接下载的网络状态集合
                        .supportMultiProcess(true) //是否支持多进程，true支持
                        .asyncInit(true) //异步初始化sdk，开启可减少初始化耗时
                        //.httpStack(new MyOkStack3())//自定义网络库，demo中给出了okhttp3版本的样例，其余请自行开发或者咨询工作人员。
                        .build());
    }


    //
    //        第三方屏幕适配
    //        AutoSizeConfig.getInstance()
//                .setCustomFragment(true)
//                .setOnAdaptListener(new onAdaptListener() {
//                    @Override
//                    public void onAdaptBefore(Object target, Activity activity) {
//                        AutoSizeLog.d(String.format(Locale.ENGLISH, "%s onAdaptBefore!", target.getClass().getName()));
//                    }
//                    @Override
//                    public void onAdaptAfter(Object target, Activity activity) {
//                        AutoSizeLog.d(String.format(Locale.ENGLISH, "%s onAdaptAfter!", target.getClass().getName()));
//                    }
//                });





//    App Key : cef72cef77c2bebdf87fc6fb93b65c9d
//    Secret Key : $2a$12$0/z1jtT5Bm7tiJYhSjv4pehL.QIr68wPiyUMB6gRDUokXmK.rFj1q

    private void initMeiqia() {
        MQConfig.init(this, meiqikey, new OnInitCallback() {
            @Override
            public void onSuccess(String clientId) {

            }

            @Override
            public void onFailure(int code, String message) {

            }
        });





    }

    public static String getCodeString() {
        return codeString;
    }

    /**
     * 判断当前进程是否是应用的主进程
     *
     * @return
     */
    public boolean isMainProcess() {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return getApplicationInfo().packageName.equals(appProcess.processName);
            }
        }
        return false;
    }


    public void post(Runnable r) {
        mainThreadHandler.post(r);
    }

    public void postDelay(Runnable r, int delayMillis) {
        mainThreadHandler.postDelayed(r, delayMillis);
    }


    public User getUser() {
        return user;
    }

    @Override
    public boolean isDebug() {
        return BuildConfig.DEBUG;
    }


    public Cache getCache() {
        return cache;
    }

    public PlaceManager getPlaceManager() {
        return placeManager;
    }


    public String getRan() {
        return ran;
    }
}
